<template>
    <div>
        <!-- <el-upload :action="uploadApi" :before-upload="beforeAvatarUpload" :data="{file_type:'image'}" :headers="headers" :on-success="handleAvatarSuccess" :show-file-list="false">
            <div class="avatar-uploader">
                <img :src="imageUrl" class="avatar" v-if="imageUrl" />
                <i class="el-icon-plus avatar-uploader-icon" v-else></i>
            </div>
        </el-upload>-->

        <div v-if="revalue != '' && isShow">
            <ul class="el-upload-list el-upload-list--picture-card">
                <li :style="'width: ' + size + 'px;height: ' + size + 'px'" class="el-upload-list__item is-ready"
                    tabindex="0">
                    <div>
                        <img :src="revalue" alt class="el-upload-list__item-thumbnail" />
                        <span class="el-upload-list__item-actions">
                            <span @click="deleteMaterial" class="el-upload-list__item-delete">
                                <i class="el-icon-delete" />
                            </span>
                            <span @click="zoomMaterial" class="el-upload-list__item-preview">
                                <i class="el-icon-view" />
                            </span>
                        </span>
                    </div>
                </li>
            </ul>
        </div>
        <div :style="'width: ' +
            size +
            'px;height: ' +
            size +
            'px;' +
            'line-height:' +
            size +
            'px;'
            " @click="toSeleteMaterial" class="el-upload el-upload--picture-card" tabindex="0" v-else>
            <i class="el-icon-plus" />
        </div>
        <el-dialog :visible.sync="DialogVisible" append-to-body title="" width="70%" class="">
            <el-container style="padding-top: 0;">
                <!-- 左侧菜单栏 -->
                <div v-loading="false" class="leftMenu">
                    <div class="addBtn">
                        <el-button size="small" type="primary" @click="toForm()">添加分组</el-button>
                    </div>
                    <div class="leftMenuBox">
                        <el-menu default-active="0" class="el-menu-vertical-demo " style="margin-top: 45px;">
                            <el-menu-item :index="index + ''" v-for="(item, index) in menuBarList" :key="index"
                                @click="menubarFun(item.mask)">
                                <div class="flexSB">
                                    <span slot="title">{{ item.name }}</span>
                                    <div style="width: 30px;" class="flexSB">
                                        <i class="el-icon-edit" style="font-size: 14px;" @click="toForm(item)"></i>
                                        <i class="el-icon-delete"
                                            style="font-size: 14px;margin-left: 10px;color: rgb(212, 75, 75);"
                                            @click.stop="openDel(item.id)"></i>
                                    </div>
                                </div>
                            </el-menu-item>
                        </el-menu>
                    </div>
                </div>
                <div style="margin-right: 150px;">
                </div>
                <el-main>
                    <div class="titleBox">
                        文件素材库
                    </div>
                    <el-card>
                        <div slot="header">
                            <el-row>
                                <el-col :span="14" style="display: flex; align-items: center"></el-col>
                                <el-col :span="10">
                                    <div class="flex align-center">
                                        <el-input placeholder="请输入文件名称" style="width: 200px" clearable
                                            v-model="page.name"></el-input>
                                        <el-button size="small" @click="getMedia('init')" style="margin-left: 10px"
                                            type="success">查询</el-button>
                                        <el-upload :action="uploadApi" :before-upload="beforeUpload" :show-file-list="false"
                                            :data="{ type: 'image', group: page.group }" :file-list="fileList"
                                            :headers="headers" :on-progress="handleProgress" :on-success="handleSuccess"
                                            multiple>
                                            <el-button size="small" style="margin-left: 10px" type="primary">上传</el-button>
                                        </el-upload>

                                        <!-- <el-button size="small" style="margin-left: 10px" type="success"
                                            @click="checkboxBtn = !checkboxBtn">多选</el-button> -->

                                        <el-button size="small" @click="batchDel()" style="margin-left: 10px"
                                            type="danger">批量删除</el-button>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                        <div v-loading="tableLoading">
                            <el-alert :closable="false" center show-icon title="暂无数据" type="info"
                                v-if="tableData.length <= 0" />
                            <el-row :gutter="5">
                                <div class="pb-10">
                                    <el-checkbox-group v-model="urls" @change="changeFun" :max="checkboxNum">

                                        <el-col :span="4" style="margin-top: 4px" v-for="(item, index) in tableData"
                                            :key="index">
                                            <el-card :body-style="{ padding: '5px' }">
                                                <el-image :preview-src-list="[item.full_path]" :src="item.full_path"
                                                    :z-index="999" fit="contain" style="width: 100%; height: 100px" />
                                                <div>
                                                    <div class="pd-10">
                                                        <!-- <el-tag title="item.name" type="info">{{item.name}}</el-tag> -->
                                                        <a :title="item.name" class="text-line1 font-12"
                                                            v-if="item.name">{{ item.name }}</a>
                                                        <a :title="item.name" class="text-line1 font-12 color-999"
                                                            v-else>----</a>

                                                        <el-input v-if="fileNameShow == index" v-model="fileName"
                                                            placeholder="请输入文件名"></el-input>

                                                    </div>
                                                    <el-checkbox :label="item.full_path"
                                                        class="material-name">选择</el-checkbox>
                                                    <el-row>
                                                        <el-col :span="24" class="col-do flex">
                                                            <el-popconfirm @confirm="materialDel(item)"
                                                                title="这是一段内容确定删除吗？">
                                                                <el-button size="mini" slot="reference" style="border: none;color: red;margin-top: 5px;">删除</el-button>
                                                         
                                                            </el-popconfirm>

                                                            <el-button v-if="fileNameShow != index" size="medium"
                                                                type="text" @click="fileNameShow = index">修改</el-button>

                                                            <el-button v-else @click="materialUpdate(item, index)"
                                                                size="medium" type="text">确定</el-button>

                                                        </el-col>
                                                    </el-row>
                                                </div>
                                            </el-card>
                                        </el-col>
                                    </el-checkbox-group>
                                </div>
                            </el-row>
                            <div class="pt-10">
                                <el-pagination :current-page.sync="page.page" :page-size="page.limit" :page-sizes="[12, 24]"
                                    :total="page.total" @current-change="pageChange" @size-change="sizeChange"
                                    class="pagination" layout="total, sizes, prev, pager, next, jumper" />
                            </div>
                        </div>
                    </el-card>
                </el-main>
            </el-container>
            <span class="dialog-footer" slot="footer">
                <el-button @click="DialogVisible = false">取 消</el-button>
                <el-button @click="sureUrls" type="primary">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog :visible.sync="mediaVisible" append-to-body width="35%">
            <img :src="revalue" alt style="width: 100%" />
        </el-dialog>

        <!-- 添加分组 -->
        <el-dialog :visible.sync="addGroupShow" append-to-body title="" width="800px">
            <div style="padding: 30px;padding-top: 50px;">
                <el-form :model="form">
                    <el-form-item label="分组名">
                        <el-input placeholder="请输入分组名" style="width: 500px" v-model="form.name"></el-input>
                    </el-form-item>
                    <el-form-item label="分组标识">
                        <el-input placeholder="请输入分组标识" style="width: 485px" v-model="form.mask"></el-input>
                    </el-form-item>
                </el-form>
                <div class="dialog-footer" style="margin-left: 450px;margin-top: 50px;" slot="footer">
                    <el-button @click="closeBox">取 消</el-button>
                    <el-button @click="submit" type="primary">确 定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getStorage } from "@/utils/auth";
export default {
    props: {
        type: {
            default: "image",
            type: String,
        },
        value: {
            type: String,
        },
        size: {
            default: "140",
            type: String,
        },
        index: {
            type: Number,
            default: null,
        },

        isShow: {
            type: Boolean, //不回显图片，默认回显
            default: true
        },
    },
    model: {

        prop: 'value',
        // 定义由 $emit 传递变量的名称
        event: 'set-content'
    },
    data() {
        return {
            imageUrl: "",
            fileName: '',
            fileNameShow: -1,
            checkboxBtn: false,
            addGroupShow: false,
            worksId: '',
            form: {
                name: '',
                mask: ''
            },
            // headers: {
            //     Authorization: 'Bearer ' + getStorage('Authorization'),
            // },
            DialogVisible: false,
            tableLoading: false,
            menubaLoading: false,
            revalue: this.value,
            tableData: [],
            mediaVisible: false,
            checkboxNum: 99,
            page: {
                page: 1,
                limit: 12,
                total: 0,
                name: null,
                group: null
            },
            urls: [],
            menuBarList: [],

            fileList: [
                {
                    name: 'file',
                    type: 'image',
                    group: 'by_alex',
                    file: '',
                }],
            idArray: [],
            addType: 'create',
        };
    },
    mounted() {
        this.$nextTick(() => { });
    },
    computed: {
        ...mapGetters(["uploadApi"]),

        headers() {
            return {
                Authorization: "Bearer " + this.$store.state.user.token,
            };
        },

    },
    watch: {
        value(val) {
            this.revalue = val;
        },
        revalue: function (val) {
            if (this.index !== null) {
                this.$emit("set-content", { path: val, index: this.index });
            } else {
                this.$emit("set-content", val);
            }
        },

        checkboxBtn(val, oldVal) {
            console.log(val, oldVal)

            if (val) {
                this.checkboxNum = 99
            } else {
                this.checkboxNum = 1
            }
        },
    },
    methods: {

        openDel(id) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.del(id)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },
        del(id) {
            this.$request.del('/file-group/delete/' + id).then((res) => {
                this.$message.success('删除成功')
                this.getLeftMenuBar() //重新请求数据

            })
        },

        toForm(form = null) {
            this.addGroupShow = true //打开弹出框
            if (form != null) {
                this.addType = 'update'
                this.worksId = form.id
                this.form = form
            } else {
                this.addType = 'create'
                this.worksId = ""
                this.form = {
                    name: '',
                    mask: ''
                }
            }
        },

        closeBox() {
            this.addType = 'create'
            this.addGroupShow = false
            this.form = {
                name: '',
                mask: ''
            }
        },
        //提交
        submit() {
            if (!(this.form.name && this.form.mask)) {
                this.$message({
                    message: '请将信息填写完整！',
                    type: 'warning'
                });
                return
            }
            if (this.addType == 'create') {
                this.$request.post('/file-group/create', this.form).then((res) => {
                    this.$message({
                        message: '添加成功',
                        type: 'success'
                    });

                    this.getLeftMenuBar() //重新请求数据
                    this.closeBox()

                })
            } else {
                this.$request.put('/file-group/update/' + this.worksId, this.form).then((res) => {
                    console.log(res)
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.getLeftMenuBar() //重新请求数据
                    this.closeBox()


                })
            }
        },
        changeFun(val) {
            // 使用 filter 方法删除特定 id 的元素
            this.idArray = this.tableData.filter(item => val.includes(item.full_path)).map(matchedItem => matchedItem.id);
        },
        materialUpdate(item, index) {

            if (this.fileName == '') {
                return this.$message.warning("请输入文件名");
            }
            this.$request.put("/file/update/" + item.id, {
                name: this.fileName,
                group: item.group
            }).then((res) => {
                this.$message.success("修改成功");
                this.fileNameShow = -1
                this.fileName = ''
                this.getMedia();
            });

        },
        menubarFun(group) {
            console.log("group", group)
            this.page.group = group
            this.getMedia();
        },

        zoomMaterial() {
            this.mediaVisible = true;
        },
        toSeleteMaterial() {
            //点击上传图标触发这里
            this.menubaLoading = true;
            this.DialogVisible = true;
            //this.getMedia();
            this.getLeftMenuBar();
        },
        //获取左侧菜单
        getLeftMenuBar() {
            let that = this;
            this.$request.get("/file-group/index").then((res) => {
                console.log("menuBarList", res);
                that.menubaLoading = false;
                that.menuBarList = res;
                if (res) {
                    that.page.group = that.menuBarList[0].mask
                }
                that.getMedia();
            });
        },
        getMedia(type = "") {
            this.tableLoading = true;
            if (type == "init") {
                this.page.page = 1;
            }
            this.$request.get("/file/index", this.page).then((res) => {
                this.tableData = res.items;
                this.page.total = res.page.total;
                console.log(res);
                this.tableLoading = false;
            });
        },
        materialDel(item) {
            this.$request.del("/file/delete", { id: item.id }).then((res) => {
                this.$message.success("删除成功");
                // this.idArray = [] //批量删除
                //this.checkboxNum = 1
                this.getMedia();
            });
        },

        batchDel() {
            if (this.idArray.length == 0) return this.$message.warning("请选择图片");
            let parameter;

            parameter = this.idArray

            this.$request.del("/file/delete", { id: parameter }).then((res) => {
                this.$message.success("删除成功");
                this.idArray = []
                this.getMedia();
            });
        },


        deleteMaterial() {
            const that = this;
            this.$confirm("是否确认删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(function () {
                that.revalue = "";
                console.log(that.revalue);
            });
        },
        handleSuccess(res, file) {
            //文件上传成功时的钩子
            console.log(res, file, 'sdsds999999999999999999999999999')
            this.getMedia();
        },
        handleProgress() {
            //文件上传时的钩子
        },
        beforeUpload(file) {
            //上传之前的钩子
            const isJPG =
                file.type === "image/jpeg" ||
                file.type === "image/png" ||
                file.type === "image/gif" ||
                file.type === "image/jpg";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error("上传图片只能是 JPG、PNG、GIF、JPEG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },
        sureUrls() {
            this.revalue = this.urls[0];
            this.DialogVisible = false;
            console.log('this.urls', this.urls)
            this.urls = []
        },
        sizeChange(val) {
            this.page.page = 1;
            this.page.limit = val;
            this.getMedia();
        },
        pageChange(val) {
            this.page.page = val;
            this.getMedia();
        },
    },
};
</script>

<style lang="scss" scoped>
.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.leftMenu {
    width: 150px;
    height: 100%;
    background-color: #ffffff;
    box-shadow: #d1d1d1 0 0 5px;
    position: absolute;
    bottom: 0;
}


.leftMenuBox {
    width: 150px;
    height: 100%;
    background-color: #ffffff;
    box-shadow: #d1d1d1 0 0 5px;
    overflow: auto;
    position: absolute;
    bottom: 0;
}

.leftMenuBox::-webkit-scrollbar {
    width: 0;
    height: 0;
}

/deep/ .el-dialog__body {
    padding: 0;
}

/deep/ .el-card__body,
.el-main {
    padding-top: 0;
}

/deep/ .el-dialog__header {
    padding: 0;
}

.titleBox {
    margin: 20px;
    font-size: 16px;
}

.addBtn {
    padding: 10px 35px;
    position: absolute;
    z-index: 999;
    background-color: #ffffff;
}

.flexSB {
    display: flex;
    justify-content: space-between;
    align-items: center;
}</style>